from django.shortcuts import render, redirect, reverse
from repository import models
from web.forms import BusinessUnitForm, ServerForm


# Create your views here.
def index(request):
	return render(request, 'index.html')


def business_unit_list(request):
	all_business_units = models.BusinessUnit.objects.all().order_by('id')
	return render(request, 'business_unit_list.html', {'all_business_units': all_business_units})


def business_unit_change(request, edit_id=None):
	obj = models.BusinessUnit.objects.filter(pk=edit_id).first()
	form_obj = BusinessUnitForm(instance=obj)
	if request.method == 'POST':
		form_obj = BusinessUnitForm(request.POST, instance=obj)
		if form_obj.is_valid():
			form_obj.save()
			return redirect(reverse('web:business_unit_list'))

	return render(request, 'form.html', {'form_obj': form_obj})


def server_list(request):
	all_servers = models.Server.objects.all().order_by('id')
	return render(request, 'server_list.html', {'all_servers': all_servers})


def server_change(request, edit_id=None):
	obj = models.Server.objects.filter(pk=edit_id).first()
	form_obj = ServerForm(instance=obj)
	if request.method == 'POST':
		form_obj = ServerForm(request.POST, instance=obj)
		if form_obj.is_valid():
			form_obj.save()
			return redirect(reverse('web:server_list'))

	return render(request, 'form.html', {'form_obj': form_obj})


def server_detail(request, pk):
	server = models.Server.objects.filter(pk=pk).first()
	all_nics = server.nic_list.all().order_by('pk')
	all_memories = server.memory_list.all().order_by('slot')
	all_disks = server.disk_list.all().order_by('slot')
	return render(request,
				  'server_detail.html',
				  {
					  'server': server,
					  'all_nics': all_nics,
					  'all_memories': all_memories,
					  'all_disks': all_disks,
				  })


def server_record(request, pk):
	all_records = models.AssetRecord.objects.filter(server_id=pk).order_by('-create_at')
	return render(request, 'server_record.html', {'all_records': all_records})
